package com.kaili.basic.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.kaili.basic.enums.DeviceEunm;
import com.kaili.basic.enums.DeviceStatusEunm;
import com.kaili.basic.mapper.*;
import com.kaili.basic.pojo.dto.*;
import com.kaili.basic.pojo.entity.*;
import com.kaili.basic.pojo.vo.*;
import com.kaili.basic.service.BaseUserService;
import com.kaili.common.pojo.entity.BaseEmployee;
import com.kaili.common.response.CommonStatus;
import com.kaili.common.response.RestStatus;
import com.kaili.common.util.DateUtil;
import com.kaili.common.util.LoginDetailUtils;
import io.swagger.models.auth.In;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.kaili.basic.service.IDeviceService;

import java.util.*;

/**
*  service实现类
* @author:zhouyijian
* @Time: 2019-07-24
* @Copyright: ©  杭州凯立通信有限公司 版权所有
* @Warning: 本内容仅限于公司内部传阅,禁止外泄或用于其它商业目的
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, MdmDeviceEntity>  implements IDeviceService {

    @Autowired
    BaseUserService baseUserService;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private OrgMapper orgMapper;
    @Autowired
    private GroupMapper groupMapper;
    @Autowired
    private DeviceSignMapper deviceSignMapper;
    @Autowired
    private BaseEmployeeMapper employeeMapper;
    @Autowired
    DeviceOnlineMapper deviceOnlineMapper;
    @Autowired
    private GlobalClobsMapper globalClobsMapper;
    @Autowired
    private DeviceCommandMapper deviceCommandMapper;

    @Override
    public RestStatus doCreateDevice(MdmDeviceAddDto dto) {

        if(dto==null){
            return CommonStatus.DEVICE_DATA_EMPTY;
        }
        Boolean result =DeviceNotExists(dto,null);
        if(result){
            MdmDeviceEntity entity =setDefaultValue(dto);
            deviceMapper.insert(entity);
        }
        return CommonStatus.ADD_OK;
    }


    @Override
    public RestStatus deleteByImei(Integer id) {
        Integer employeeId=LoginDetailUtils.getCurrentEmployeeId();
        MdmDeviceEntity entity = new MdmDeviceEntity();
        entity.setId(id);
        entity.setModifyBy(employeeId);
        entity.setModifyTime(new Date());
        entity.setRdStatus(DeviceStatusEunm.DELETE.getCode());
        deviceMapper.updateById(entity);
        return CommonStatus.DELETE_OK;
    }

    @Override
    public RestStatus switchDeviceStatus(String imei) {
        Integer employeeId=LoginDetailUtils.getCurrentEmployeeId();
        MdmDeviceEntity entity = new MdmDeviceEntity();
        MdmDeviceVO deviceVO =deviceMapper.getIsActionByImei(imei);
        if(deviceVO==null){
            return CommonStatus.DEVICE_DATA_EMPTY;
        }
        if(DeviceStatusEunm.DEVICE_ON.getCode().equals(deviceVO.getIsAction())){
            deviceVO.setIsAction(DeviceStatusEunm.DEVICE__OFF.getCode());
        }else {
            deviceVO.setIsAction(DeviceStatusEunm.DEVICE_ON.getCode());
        }
        deviceVO.setModifyBy(employeeId);
        deviceVO.setModifyTime(new Date());
        BeanUtils.copyProperties(deviceVO,entity);
        deviceMapper.updateById(entity);
        return CommonStatus.UPDATE_OK;
    }


    @Override
    public RestStatus updateDeviceByImei(MdmDeviceAddDto dto) {
        Integer employeeId=LoginDetailUtils.getCurrentEmployeeId();
        MdmDeviceEntity entity = new MdmDeviceEntity();
        BeanUtils.copyProperties(dto,entity);
        deviceMapper.updateById(entity);
        entity.setModifyBy(employeeId);
        entity.setModifyTime(new Date());
        deviceMapper.updateById(entity);
        return CommonStatus.UPDATE_OK;
    }

    @Override
    public void doCreateDeviceImport(MdmDeviceImportDTO dto) {
        MdmDeviceEntity entity = new MdmDeviceEntity();
        Boolean result =DeviceNotExists(null,dto);
        //设备不存在即可新增
        if(result){
            int orgId =orgMapper.getOrgIdByName(dto.getOrgName());
            int groupId =groupMapper.getGroupIdByName(dto.getGroupName());
            BaseEmployee baseEmployee =employeeMapper.getEmpByName(dto.getCreateName());
            entity.setImei(dto.getImei()!=null?dto.getImei():"");
            entity.setSn(dto.getSn()!=null?dto.getSn():"");
            entity.setModel(dto.getModel()!=null?dto.getModel():"");
            entity.setMac(dto.getMac()!=null?dto.getMac():"");
            entity.setOrgId(orgId);
            entity.setActionTime(dto.getActionTime());
            entity.setRdStatus(DeviceStatusEunm.NORMAL.getCode());
            entity.setCreateBy(baseEmployee!=null?baseEmployee.getId():0);
            entity.setCreateTime(new Date());
            entity.setDeviceName(dto.getDeviceName()!=null?dto.getDeviceName():"");
            entity.setGroupId(groupId);
            entity.setVersion(dto.getVersion()!=null?dto.getVersion():"");
            if(StringUtils.isEmpty(dto.getPlateformName())){ //平台
                entity.setPlatformId(DeviceEunm.ANDROID.getCode());//默认安卓
            }else{
                if(dto.getPlateformName().equalsIgnoreCase(DeviceEunm.IOS.getMessage())){
                    entity.setPlatformId(DeviceEunm.IOS.getCode());//IOS
                }else if(dto.getPlateformName().equalsIgnoreCase(DeviceEunm.ANDROID.getMessage())){
                    entity.setTypeId(DeviceEunm.PHONE.getCode());//PHONE
                }
            }
            //设备归属
            if(StringUtils.isEmpty(dto.getBelongName())){
                entity.setBelongId(DeviceEunm.COMPANY_BELONG.getCode());//默认归属单位
            }else{
                if(dto.getBelongName().equals(DeviceEunm.PERSON_BELONG.getMessage())){
                    entity.setBelongId(DeviceEunm.PERSON_BELONG.getCode());//个人
                }else{
                    entity.setBelongId(DeviceEunm.COMPANY_BELONG.getCode());//归属单位
                }
            }
            //设备类型
            if(StringUtils.isEmpty(dto.getTypeName())){ //设备类型
                entity.setTypeId(DeviceEunm.PDA.getCode());//默认PDA
            }else if (dto.getTypeName().equals(DeviceEunm.PHONE.getMessage())){
                entity.setTypeId(DeviceEunm.PHONE.getCode());
            }else if(dto.getTypeName().equals(DeviceEunm.PDA.getMessage())){
                entity.setTypeId(DeviceEunm.PDA.getCode());
            }else if(dto.getTypeName().equals(DeviceEunm.PAD.getMessage())){
                entity.setTypeId(DeviceEunm.PAD.getCode());
            }else{
                entity.setTypeId(DeviceEunm.OTHER_TYPE.getCode());
            }
            //设备操作
            if(DeviceStatusEunm.DEVICE__OFF.getMessage().equals(dto.getIsAction())){
                entity.setIsAction(DeviceStatusEunm.DEVICE__OFF.getCode());
            }else{
                entity.setIsAction(DeviceStatusEunm.DEVICE_ON.getCode());
            }
            deviceMapper.insert(entity);
        }
    }

    @Override
    public Page<MdmDeviceVO> queryPageList(MdmDeviceQueryDto dto) {
        Page<MdmDeviceVO>  page= new Page<MdmDeviceVO>();
        MdmDeviceEntity entity = new MdmDeviceEntity();
        BeanUtils.copyProperties(dto,entity);
        List<MdmDeviceVO> result =deviceMapper.queryPageList(entity);
        return page.setRecords(result);
    }

    @Override
    public MdmDeviceVO getDeviceById(Integer id) {
        return deviceMapper.getDeviceById(id);
    }

    @Override
    public List<MdmDeviceVO> queryListByCondition(MdmDeviceQueryDto dto) {
        MdmDeviceEntity entity = new MdmDeviceEntity();
        BeanUtils.copyProperties(dto,entity);
        List<MdmDeviceVO> list =deviceMapper.queryExportList(entity);
        return list;
    }

    private MdmDeviceEntity setDefaultValue(MdmDeviceAddDto dto){
        MdmDeviceEntity entity = new MdmDeviceEntity();
        Integer employeeId=LoginDetailUtils.getCurrentEmployeeId();
        if(StringUtils.isEmpty(dto.getSn())){
            dto.setSn(dto.getImei());   //手机若没SN默认取IMEI
        }
        if(dto.getBelongId()==0){
            dto.setBelongId(DeviceEunm.COMPANY_BELONG.getCode());//默认归属单位
        }
        if(dto.getTypeId()==0){
            dto.setTypeId(DeviceEunm.PDA.getCode());//默认PDA
        }
        if(dto.getPlatformId()==0){
            dto.setPlatformId(DeviceEunm.ANDROID.getCode());//默认安卓
        }
        BeanUtils.copyProperties(dto,entity);
        entity.setIsOrganization(DeviceEunm.ORG_BIND.getCode()); //默认绑定机构
        if(DeviceEunm.DEVICE_CREATE.getCode().equals(dto.getIsResgister())){
            //设备登记
            entity.setIsAction(DeviceStatusEunm.DEVICE__OFF.getCode());
        }
        if(DeviceEunm.DEVICE_REGISTER.getCode().equals(dto.getIsResgister())){
            //设备注册
            entity.setIsAction(DeviceStatusEunm.DEVICE_ON.getCode());
            //1.设备命令表
            MdmDeviceCommand mdmDeviceCommand = new MdmDeviceCommand();
            mdmDeviceCommand.setImei(entity.getImei());
            mdmDeviceCommand.setCreateBy(employeeId);
            deviceCommandMapper.addMdmDeviceCommand(mdmDeviceCommand);
        }
        entity.setCreateBy(employeeId);
        entity.setCreateTime(new Date());
        entity.setRdStatus(DeviceStatusEunm.NORMAL.getCode());
        return entity;
    }

    @Override
    public List<MdmDeviceVO> queryModelByTypeId(Integer typeId) {

        return deviceMapper.queryModelByTypeId(typeId);
    }

    @Override
    public MdmDeviceSumVO queryDeviceSumList(MdmDeviceSumDTO dto) {
        Date currentDate =new Date();
        //设备总数
        int deviceTotal =deviceMapper.getDeviceTotal();
        //启用设备数
        int deviceActionTotal = deviceMapper.getActionDeviceTotal();
        //在线设备
        int deviceOnLineTotal =deviceSignMapper.getDeviceOnlineTotal();

        //脱离管控设备
        MdmGlobalClobEntity globalClobEntity = new MdmGlobalClobEntity();
        globalClobEntity.setServiceCode("device_sum_server");
        globalClobEntity.setId(DeviceEunm.DEVICE_OUT_CONTROLLER.getCode());
        MdmGlobalClobVO result =globalClobsMapper.getGlobalClobsByCondition(globalClobEntity);
        Date startDate =DateUtil.systemConfigDate(Integer.parseInt(result.getRemark()),currentDate);
        MdmDeviceSumDTO deviceSumDTO = new MdmDeviceSumDTO();
        deviceSumDTO.setStartTime(startDate);
        deviceSumDTO.setEndTime(currentDate);
        int deviceOutControllerTotal =deviceMapper.getDeviceOutController(deviceSumDTO);
        //告警设备
        int deviceWarnTotal =deviceMapper.getDeviceWarnTotal();
        //破解设备
        int deviceBreakTotal = deviceOnlineMapper.getDeviceBreakTotal();
        //型号分布
        List<MdmDeviceVO> deviceModelMap = deviceMapper.getDeviceModelMap();
        //设备平台
        List<MdmDeviceVO>  devicePlatformTotal =deviceMapper.getDevicePlatformTotal();
        //在线分布图
        List<MdmDeviceOnlineVo> deviceOnlineMap = deviceOnlineMapper.getDeviceOnlineMap();
        //设备状态
        List<MdmDeviceOnlineVo> deviceStatusTotal = deviceOnlineMapper.getDeviceStatusTotal();
        MdmDeviceSumVO deviceSumVO = new MdmDeviceSumVO();
        deviceSumVO.setDeviceTotal(deviceTotal);
        deviceSumVO.setDeviceBreakTotal(deviceBreakTotal);
        deviceSumVO.setDeviceModelMap(deviceModelMap);
        deviceSumVO.setDeviceOnlineMap(deviceOnlineMap);
        deviceSumVO.setDeviceOnLineTotal(deviceOnLineTotal);
        deviceSumVO.setDevicePlatformTotal(devicePlatformTotal);
        deviceSumVO.setDeviceOutControllerTotal(deviceOutControllerTotal);
        deviceSumVO.setDeviceStatusTotal(deviceStatusTotal);
        deviceSumVO.setDeviceWarnTotal(deviceWarnTotal);
        deviceSumVO.setDeviceActionTotal(deviceActionTotal);
        return deviceSumVO;
    }

    /**
     * @Desc:验证设备是否存在
     * @author:zhouyijian
     * @time: 2019/8/2 18:45
     * @param addDto
     * @param importDto
     * @return: boolean
     */
    private boolean DeviceNotExists(MdmDeviceAddDto addDto, MdmDeviceImportDTO importDto){
        Map<String,Object> map =new HashMap<>();
        if(addDto!=null){
            map.put("imei",addDto.getImei());
            map.put("typeId",addDto.getTypeId());
            map.put("id",addDto.getModel()); //前台给的是主键id
        }else if(importDto!=null){
            if (importDto.getTypeName().equals(DeviceEunm.PHONE.getMessage())){
                map.put("typeId",DeviceEunm.PHONE.getCode());
            }else if(importDto.getTypeName().equals(DeviceEunm.PDA.getMessage())){
                map.put("typeId",DeviceEunm.PDA.getCode());
            }else if(importDto.getTypeName().equals(DeviceEunm.PAD.getMessage())){
                map.put("typeId",DeviceEunm.PAD.getCode());
            }else{
                map.put("typeId",DeviceEunm.OTHER_TYPE.getCode());
            }
            map.put("imei",importDto.getImei());
            map.put("model",importDto.getModel());
        }
        MdmDeviceVO device =deviceMapper.validateIsExistByImei(map);
        if(device==null){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public Page<MdmDeviceSafetyVo> queryMdmDeviceSafetyInfo(Page<MdmDeviceSafetyVo> page, MdmDeviceSafetyDto safetyDto) {
        if(safetyDto.getDate()==null){
            safetyDto.setDate(Calendar.getInstance().getTime());
        }
        List<MdmDeviceSafetyVo> mdmDeviceOnlines = deviceMapper.queryMdmDeviceSafety(page,safetyDto);

        for (MdmDeviceSafetyVo vo:mdmDeviceOnlines) {
            vo.setDate(safetyDto.getDate());
        }
        return page.setRecords(mdmDeviceOnlines);
    }
}
